package cn.school.demo.ui.search

import android.content.SharedPreferences
import android.graphics.Color
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.appcompat.widget.SearchView.OnQueryTextListener
import androidx.databinding.DataBindingUtil
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModelProvider
import androidx.navigation.fragment.findNavController
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import cn.school.demo.MyApplication
import cn.school.demo.R
import cn.school.demo.databinding.FragmentSearchBinding
import cn.school.demo.pojo.Article
import com.blankj.utilcode.util.GsonUtils
import com.blankj.utilcode.util.LogUtils
import com.google.gson.reflect.TypeToken
import com.mylhyl.circledialog.CircleDialog
import com.zhy.view.flowlayout.FlowLayout
import com.zhy.view.flowlayout.TagAdapter


class SearchFragment : Fragment() {
    private lateinit var viewModel: SearchViewModel
    private lateinit var binding: FragmentSearchBinding
    private var sh: SharedPreferences? = null

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        MyApplication.systemBarSetting(MyApplication.DARK, requireActivity())
        viewModel = ViewModelProvider(this).get(SearchViewModel::class.java)
        binding = DataBindingUtil.inflate(inflater, R.layout.fragment_search, container, false)
        binding.lifecycleOwner = viewLifecycleOwner
        binding.vw = this
        sh = requireActivity().getSharedPreferences(
            "SearchHistory",
            androidx.appcompat.app.AppCompatActivity.MODE_PRIVATE
        )
        val list = GsonUtils.fromJson<ArrayList<String>>(
            sh!!.getString(
                MyApplication.user!!.sfNumber.toString(),
                null
            ),
            object : TypeToken<ArrayList<String>>() {}.type
        )
        if (list.isNullOrEmpty()) {
            binding.apply {
                searchHistoryTextTextView.visibility = View.GONE
                searchFragmentDelete.visibility = View.GONE
                searchFragmentFlowlayout.visibility = View.GONE
            }
        }
        viewModel.setSearchHistory(list)
        init()
        return binding.root
    }

    private fun init() {
        binding.searchFragmentQuery.setOnQueryTextListener(object : OnQueryTextListener {
            //当点击搜索按钮时触发该方法
            override fun onQueryTextSubmit(query: String): Boolean {
                searchSubmit()
                return false
            }

            //当搜索内容改变时触发该方法
            override fun onQueryTextChange(newText: String): Boolean {
                return false
            }
        })
        binding.searchFragmentFlowlayout.apply {
            adapter = object : TagAdapter<String>(viewModel.searchHistory.value) {
                override fun getView(parent: FlowLayout, position: Int, text: String): View {
                    val tv = LayoutInflater.from(requireContext()).inflate(
                        R.layout.flow_search_history_fragment,
                        binding.searchFragmentFlowlayout, false
                    ) as TextView
                    tv.text = text
                    return tv
                }
            }
            setOnTagClickListener { _, position, _ ->
                binding.searchFragmentQuery.setQuery(
                    viewModel.searchHistory.value!![position] as CharSequence,
                    true
                )
                true
            }
        }
        viewModel.topSearchList.observe(viewLifecycleOwner) {
            binding.searchFragmentReSouText.apply {
                layoutManager = LinearLayoutManager(requireContext())
                adapter = TopSearchAdapter(it)
            }
        }
    }

    //删除搜错历史
    fun deleteSearchHistory() {
        CircleDialog.Builder()
            .setText("你确定要删除搜索历史吗？")
            .setTextColor(Color.BLACK)
            .setPositive("确定") {
                sh!!.edit().apply {
                    binding.apply {
                        searchFragmentFlowlayout.visibility = View.GONE
                        searchHistoryTextTextView.visibility = View.GONE
                        searchFragmentDelete.visibility = View.GONE
                    }
                    remove(MyApplication.user!!.sfNumber.toString())
                    commit()
                }
            }.setNegative("取消", null).show(parentFragmentManager)
    }

    //返回键
    fun gotoBack() = MyApplication.apply {
        when (navigateThing["Search"]) {
            "Article to Search" -> {
                goto(R.id.action_Search_to_Article, findNavController(), parentFragmentManager)
                navigateThing.remove("Search")
            }
        }
    }

    //搜索框
    private fun searchSubmit() {
        /*val paramMap =
            mapOf("text" to binding.searchFragmentQuery.query.toString())
        val bundle: Bundle = bundleOf(Pair("map", GsonUtils.toJson(paramMap)))*/
        MyApplication.searchContext = binding.searchFragmentQuery.query.toString()
        MyApplication.goto(
            R.id.action_Search_to_Searched,
            findNavController(),
            parentFragmentManager//,
            //bundle
        )
        when (sh!!.getString(MyApplication.user!!.sfNumber.toString(), null)) {
            null -> {
                sh!!.edit().apply {
                    putString(
                        MyApplication.user!!.sfNumber.toString(),
                        GsonUtils.toJson(mutableListOf<String>(binding.searchFragmentQuery.query.toString()))
                    )
                    commit()
                }
                viewModel.setSearchHistory(mutableListOf<String>(binding.searchFragmentQuery.query.toString()))
                binding.searchFragmentFlowlayout.adapter.notifyDataChanged()
            }
            else -> {
                val list = GsonUtils.fromJson<ArrayList<String>>(
                    sh!!.getString(
                        MyApplication.user!!.sfNumber.toString(),
                        null
                    ),
                    object : TypeToken<ArrayList<String>>() {}.type
                )
                if (list.size < 4) {
                    if (!list.contains(binding.searchFragmentQuery.query.toString()))
                        list.add(binding.searchFragmentQuery.query.toString())
                } else {
                    if (!list.contains(binding.searchFragmentQuery.query.toString())) {
                        list.removeAt(0)
                        list.add(binding.searchFragmentQuery.query.toString())
                    }
                }
                sh!!.edit().apply {
                    putString(
                        MyApplication.user!!.sfNumber.toString(),
                        GsonUtils.toJson(list)
                    )
                    commit()
                }
                viewModel.setSearchHistory(list)
                binding.searchFragmentFlowlayout.adapter.notifyDataChanged()
            }
        }
        binding.apply {
            searchHistoryTextTextView.visibility = View.VISIBLE
            searchFragmentDelete.visibility = View.VISIBLE
        }
    }

    private inner class TopSearchHolder(view: View) : RecyclerView.ViewHolder(view),
        View.OnClickListener {
        private lateinit var article: Article
        private val textView: TextView = itemView.findViewById(R.id.fragment_search_resou)

        init {
            itemView.setOnClickListener(this)
        }

        fun bind(article: Article) {
            this.article = article
            textView.text = this.article.articleName
        }

        override fun onClick(v: View?) {
            LogUtils.e("点我去文章界面！")
            MyApplication.apply {
                article = this@TopSearchHolder.article
                navigateThing["ArticleEntity"] = R.id.action_ArticleEntity_to_Search.toString()
                goto(
                    R.id.action_Search_to_ArticleEntity,
                    findNavController(),
                    parentFragmentManager
                )
            }
        }
    }

    private inner class TopSearchAdapter(var articleList: MutableList<Article>) :
        RecyclerView.Adapter<SearchFragment.TopSearchHolder>() {
        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): TopSearchHolder {
            val view = layoutInflater.inflate(R.layout.list_item_searched_resou, parent, false)
            return TopSearchHolder(view)
        }

        override fun onBindViewHolder(holder: TopSearchHolder, position: Int) {
            val article = articleList[position]
            holder.bind(article)
        }

        override fun getItemCount() = articleList.size

    }
}

